<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>编辑商品</el-breadcrumb-item>
        </el-breadcrumb>

        <!-- 卡片视图区域 -->
        <el-card>
            <!-- 消息提示 -->
            <el-alert title="编辑商品信息" type="warning" center show-icon :closable="false">
            </el-alert>
            <!-- 步骤条组件 -->
            <!-- align-center(居中效果) -->
            <el-steps :space="200" :active="activeIndex - 0" finish-status="success" align-center>
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
                <el-step title="完成"></el-step>
            </el-steps>
            <!-- 商品添加表格 -->
            <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px" label-position="top">
                <el-tabs v-model="activeIndex" :tab-position="'left'" :before-leave="beforeTabLeave" @tab-click="tabClicked">
                    <!-- 基本信息 -->
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="addForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="addForm.goods_price" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="addForm.goods_weight" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="addForm.goods_number" type="number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类" prop="goods_cat">
                            <!-- 选择商品分类的级联选择框 -->
                            <el-cascader v-model="addForm.goods_cat" :options="cateList" :props="cateProps" @change="handleChange" clearable></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 商品参数 -->
                    <el-tab-pane label="商品参数" name="1">
                        <!-- 渲染表单item项 -->
                        <el-form-item :label="item.attr_name" :key="item.attr_id" v-for="item in manyTableData">
                            <!-- 使用数组渲染复选框组 -->
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox border :label="val" v-for="(val,i) in item.attr_vals" :key="i" ></el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 商品属性 -->
                    <el-tab-pane label="商品属性" name="2">
                         <!-- 循环生成静态属性 -->
                        <el-form-item :label="item.attr_name" v-for="item in onlyTableData" :key="item.attr_id">
                            <el-input v-model="item.attr_value"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <!-- 图片上传 -->
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload :action="uploadURL" :on-preview="handlePreview" :on-remove="handleRemove" :on-success="handleSuccess" list-type="picture" :headers="headerObj">
                            <el-button size="small" type="primary">点击上传</el-button>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <!-- 富文本编辑器组件 -->
                        <quill-editor v-model="addForm.goods_introduce"></quill-editor>
                        <!-- 添加商品按钮 -->
                        <el-button type="primary" class="btnAdd" @click="addProduct">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>

        <!-- 预览图片对话框 -->
        <el-dialog title="图片预览" :visible.sync="previewVisible" width="30%">
            <img :src="previewPath" class="previewImg" />
        </el-dialog>
    </div>
</template>
<script>

import _ from 'lodash'
export default {
  data () {
    return {
      // 保存步骤条激活项索引
      activeIndex: '0',
      // 商品添加基本信息
      addForm: {
        goods_name: '',
        goods_price: 0,
        goods_weight: 0,
        goods_number: 0,
        goods_cat: [],
        // 上传图片数组
        pics: [],
        // 商品内容介绍
        goods_introduce: '商品内容描述与介绍',
        attrs: []
      },
      // 商品添加输入框验证规则
      addFormRules: {
        // 商品名称验证
        goods_name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' }
        ],
        // 价格验证
        goods_price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' }
        ],
        // 商品重量
        goods_weight: [
          { required: true, message: '请输入商品重量', trigger: 'blur' }
        ],
        // 商品数量
        goods_number: [
          { required: true, message: '请输入商品数量', trigger: 'blur' }
        ],
        // 商品分类
        goods_cat: [
          { required: true, message: '请选择商品分类', trigger: 'blur' }
        ]
      },
      // 用来保存分类数据
      cateList: [],
      // 配置级联菜单中展示的数据
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      // 商品动态参数列表
      manyTableData: [],
      // 商品静态属性列表
      onlyTableData: [],
      // 图片上传地址
      uploadURL: 'http://127.0.0.1:8888/api/private/v1/upload',
      headerObj: {
        Authorization: window.sessionStorage.getItem('token')
      },
      // 保存预览图片的url地址
      previewPath: '',
      // 控制预览图片显示对话框的显示和隐藏
      previewVisible: false
    }
  },

  created () {
    this.getCateList()
    this.getGoodsData()
  },
  methods: {
    // 根据商品id获取查询商品信息i
    async getGoodsData () {
      const { data: res } = await this.$axios.get('goods/' + this.$route.query.goods_id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品信息失败')
      };
      res.data.goods_cat = res.data.goods_cat.split(',')
      this.addForm = res.data
      var cate = []
      res.data.goods_cat.forEach(item => {
        cate.push(parseInt(item))
      })
      this.addForm.goods_cat = cate
    },
    // 商品分类级联选择框
    async getCateList () {
      const { data: res } = await this.$axios.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类数据失败')
      };
      this.cateList = res.data
    },
    handleChange () {
      // 需满足三级分类
      if (this.addForm.goods_cat.length !== 3) {
        this.addForm.goods_cat = []
      }
    },
    // 商品添加tab切换事件
    beforeTabLeave (nextTab, lastTab) {
      if (lastTab === 0) {
        this.addForm.goods_weight = parseFloat(this.addForm.goods_weight).toFixed(2)
        this.addForm.goods_number = parseInt(this.addForm.goods_number)
        this.addForm.goods_price = parseFloat(this.addForm.goods_price).toFixed(2)
        this.addForm.goods_name = this.addForm.goods_name.trim()
        if (this.addForm.goods_name === '') {
          this.$message.error('请输入商品名称')
          return false
        } else if (this.addForm.goods_price <= 0) {
          this.$message.error('商品价格不能小于0')
          return false
        } else if (this.addForm.goods_weight <= 0) {
          this.$message.error('商品重量不能小于0')
          return false
        } else if (this.addForm.goods_number <= 0) {
          this.$message.error('商品数量不能小于0')
          return false
        } else if (this.addForm.goods_cat.length !== 3) {
          this.$message.error('未选中完整的商品分类')
          return false
        };
      };
    },
    // tab栏点击事件
    async tabClicked () {
      // 点击商品动态参数
      if (this.activeIndex == 1) {
        const { data: res } = await this.$axios.get('goods/' + this.$route.query.goods_id)
        var manyData = res.data.attrs.filter(item => item.attr_sel === 'many')
        manyData.forEach(element => {
          element.attr_vals = element.attr_vals ? element.attr_vals.split(',') : []
        })
        this.manyTableData = manyData
      } else if (this.activeIndex == 2) {
        var onlyData = this.addForm.attrs.filter(item => item.attr_sel == 'only')
        this.onlyTableData = onlyData
      } else if (this.activeIndex == 3) {
        var html = ''
        this.addForm.pics.forEach(item => {
          html += `
                        <li tabindex="0" class="el-upload-list__item is-success">
                        <img src='${item.pics_big_url}' alt="" class="el-upload-list__item-thumbnail">
                        <a class="el-upload-list__item-name">
                            <i class="el-icon-document"></i> 
                        </a>
                        <label class="el-upload-list__item-status-label">
                            <i class="el-icon-upload-success el-icon-check"></i>
                        </label>
                        <i class="el-icon-close"></i>
                        <i class="el-icon-close-tip">按 delete 键可删除</i>
                        </li>`
        })

        var ul = document.querySelector('.el-upload-list')

        ul.innerHTML = html
        // .appendChild(li)
      };
    },
    // 商品图片预览 参数file是要预览的文件
    handlePreview (file) {
      // 图片地址赋值给previewPath
      this.previewPath = file.response.data.url
      this.previewVisible = true
    },
    // 商品图片删除 参数file是要删除的文件
    handleRemove (file) {
      // 获取用户点击删除的那个图片的临时路径
      const filePath = file.response.data.tmp_path
      // 图片路径匹配找到该项的数组索引 使用findIndex来查找符合条件的索引
      const index = this.addForm.pics.findIndex(item => item.pic === filePath)
      // 移除索引对应的图片
      this.addForm.pics.splice(index, 1)
    },
    // 当图片上传成功后触发执行，参数res是后台返回的结果
    handleSuccess (res) {
      this.addForm.pics = []
      // 将服务器返回的图片的临时路径保存到addForm表单的pics数组中
      this.addForm.pics.push({ pic: res.data.tmp_path })
    },
    // 点击按钮，添加商品
    addProduct () {
      //    表单预校验
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return this.$message.error('请填写完整的商品信息')
        const form = _.cloneDeep(this.addForm)
        // 将goods_cat从数组转换为"1,2,3"字符串形式
        form.goods_cat = form.goods_cat.join(',')
        // 将manyTableData（动态参数）处理添加到attrs
        this.manyTableData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals.join(',') })
        })
        // 将onlyTableData（静态属性）处理添加到attrs
        this.onlyTableData.forEach(item => {
          form.attrs.push({ attr_id: item.attr_id, attr_value: item.attr_vals })
        })
        // console.log(form)

        const { data: res } = await this.$axios.put('goods' + this.$route.query.goods_id, form)
        if (res.meta.status !== 201) {
          return this.$message.error('添加商品失败')
        };
        this.$message.success('添加商品成功')
        // 编程式导航跳转到商品列表
        this.$router.push('/goods')
      })
    }
  },
  // 计算属性
  computed: {
    // 获取商品最后一级分类的id
    cateId () {
      if (this.addForm.goods_cat.length === 3) {
        return this.addForm.goods_cat[2]
      };
      return null
    }
  }
}
</script>
<style lang="less" scoped>
    .el-checkbox{
        margin: 0 10px 0 0 !important;
    }
    .el-dialog img{
        width: 100%;
    }
    .btnAdd{
        margin-top:15px
    }
</style>
